import java.util.*;


public class Main {
    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
    public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1 == null || pHead2 == null){
            return null;
        }
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        while (p1 != p2){
            p1 = p1 == null?pHead2:p1.next;
            p2 = p2 == null?pHead1:p2.next;
        }
        return p1;
    }

    public static void main(String[] args) {
        ListNode c1 = new ListNode(6);
        ListNode c2 = new ListNode(7);
        c1.next = c2;
        ListNode a1 = new ListNode(1);
        ListNode a2 = new ListNode(2);
        ListNode a3 = new ListNode(3);
        a1.next = a2;
        a2.next = a3;
        a3.next = c1;
        ListNode b1 = new ListNode(4);
        ListNode b2 = new ListNode(5);
        b1.next = b2;
        b2.next = c1;
        ListNode p = FindFirstCommonNode(a1,b1);
        while (p != null){
            System.out.println(p.val);
            p = p.next;
        }
    }
}
